import React, { Component } from 'react';
import { Select } from 'antd';
const Option = Select.Option;

interface IProps {
  optionList: {
    name: string;
    id: number;
  }[];
  onChange: Function;
  placeholder?: string;
  record?: any;
}
interface IState {
  value: any;
}
export class SelectAll extends Component<IProps, IState> {
  constructor(props: any) {
    super(props);
    this.state = {
      value: [],
    };
  }
  componentDidMount() {
    this.setState({ value: this.props.record?.id });
  }
  handleChange = (value: any) => {
    this.props.onChange(this.state.value);
    // 第一个是全选 再选择其他时，去掉全选
    // 第一个不是全选 而后再选全选时，只保留全选
    // 第一个是全选 且只有全选时，只保留全选
    // if (value[0] === 'all' && value.length > 1) {
    //   this.setState({ value: value.filter((item: string) => item !== 'all') }, () => {
    //     this.props.onChange(this.state.value);
    //   });
    // } else if (
    //   (value[0] !== 'all' && new Set(value).has('all')) ||
    //   (value[0] === 'all' && value.length === 1)
    // ) {
    //   this.setState({ value: 'all' }, () => {
    //     this.props.onChange(this.props.optionList.map((item: any) => item.id));
    //   });
    // } else {
    //   this.setState({ value }, () => {
    //     this.props.onChange(this.state.value);
    //   });
    // }
  };

  render() {
    const { optionList, placeholder } = this.props;
    const { value } = this.state;
    return (
      <Select
        value={value}
        onChange={this.handleChange}
        allowClear
        showSearch
        placeholder={placeholder || '请选择'}
        style={{ width: 300 }}
        mode="multiple"
        optionFilterProp="children"
        filterOption={(input, option: any) =>
          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
      >
        {/* <Option key="all" value="all">
          全选
        </Option> */}
        {optionList.map((item: any) => {
          return (
            <Option key={item.id} value={item.id}>
              {item.name}
            </Option>
          );
        })}
      </Select>
    );
  }
}
